package com.tongbo.mobilesafe.db.dao;

import java.util.ArrayList;
import java.util.List;

import com.tongbo.mobilesafe.db.BlackNumberDBHelper;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class BlackNumberDao {
	@SuppressWarnings("unused")
	private Context context;
	private BlackNumberDBHelper dbHelper;
	public BlackNumberDao(Context context){
		this.context = context;
		dbHelper = new BlackNumberDBHelper(context);
	}
	/**
	 * 查询是否在黑名单
	 * @param number 手机号码
	 * @return 是否在黑名单
	 */
	public boolean find(String number){
		boolean result = false;
		System.out.println(dbHelper==null);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		String sql = "select number from blacknumber where number=?";
		if(db.isOpen()){
			Cursor cursor = db.rawQuery(sql, new String[]{number});
			if(cursor.moveToNext()){
				result = true;
			}
			cursor.close();
			db.close();
		}
		return result;
	}
	/**
	 * 添加号码到黑名单
	 * @param number 要添加的手机号
	 */
	public void add(String number){
		if(find(number)){
			return;
		}
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		String sql = "insert into blacknumber(number) values(?)";
		if(db.isOpen()){
			db.execSQL(sql,new Object[]{number});
			db.close();
		}
	}
	/**
	 * 从黑名单中删除指定的手机号
	 * @param number
	 */
	public void delete(String number){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		String sql = "delete from blacknumber where number=?";
		if(db.isOpen()){
			db.execSQL(sql,new Object[]{number});
			db.close();
		}
	}
	/**
	 * 更新
	 * @param oldNumber 旧的手机号
	 * @param newNumber 新的手机号
	 */
	public void update(String oldNumber,String newNumber){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		String sql = "update blacknumber set number=? where number=?";
		if(db.isOpen()){
			db.execSQL(sql,new Object[]{newNumber,oldNumber});
			db.close();
		}
	}
	public List<String> getAllNumbers(){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		List<String> numbers = new ArrayList<String>();
		String sql = "select number from blacknumber";
		if(db.isOpen()){
			Cursor cursor = db.rawQuery(sql,null);
			while(cursor.moveToNext()){
				String number = cursor.getString(0);
				numbers.add(number);
			}
			cursor.close();
			db.close();
		}
		return numbers;
	}
}